
package com.shiku.imserver.common.packets;


import com.shiku.imserver.common.message.ChatMessage;
import org.tio.core.intf.Packet;


public class ImPacket
        extends Packet
        implements IPacket {
    private static final long serialVersionUID = 2000118564569232098L;
    protected byte[] bytes;
    private short command;
    private ChatMessage message;


    public ImPacket() {
    }


    public ImPacket(byte[] bytes) {

        this.bytes = bytes;

    }


    public ImPacket(short command, byte[] body) {

        this(body);

        setCommand(command);

    }


    public ImPacket(short command) {

        this(command, null);

    }


    public void releaseMessageBody() {

        setBytes(null);

    }


    public static byte encodeEncrypt(byte bs, boolean isEncrypt) {

        if (isEncrypt) {

            return (byte) (bs | Byte.MIN_VALUE);

        }

        return 0;

    }


    public static boolean decodeCompress(byte version) {

        return ((0x40 & version) != 0);

    }


    public static byte encodeCompress(byte bs, boolean isCompress) {

        if (isCompress) {

            return (byte) (bs | 0x40);

        }


        return (byte) (bs & 0x3F);

    }


    public static boolean decodeHasSynSeq(byte maskByte) {

        return ((0x20 & maskByte) != 0);

    }


    public static byte encodeHasSynSeq(byte bs, boolean hasSynSeq) {

        if (hasSynSeq) {

            return (byte) (bs | 0x20);

        }


        return (byte) (bs & 0x5F);

    }


    public static boolean decode4ByteLength(byte version) {

        return ((0x10 & version) != 0);

    }


    public static byte encode4ByteLength(byte bs, boolean is4ByteLength) {

        if (is4ByteLength) {

            return (byte) (bs | 0x10);

        }


        return (byte) (bs & 0x6F);

    }


    public static byte decodeVersion(byte version) {

        return (byte) (0xF & version);

    }


    public int calcHeaderLength(boolean is4byteLength) {

        int ret = 4;

        if (is4byteLength) {

            ret += 2;

        }

        if (getSynSeq().intValue() > 0) {

            ret += 4;

        }

        return ret;

    }


    @Override
    public short getCommand() {

        return this.command;

    }


    @Override
    public void setCommand(short type) {

        this.command = type;

    }


    @Override
    public byte[] getBytes() {

        return this.bytes;

    }


    @Override
    public void setBytes(byte[] bytes) {

        this.bytes = bytes;

    }


    @Override
    public String logstr() {

        return String.valueOf(this.command);

    }


    @Override
    public ChatMessage getMessage() {

        return this.message;

    }


    @Override
    public void setMessage(ChatMessage message) {

        this.message = message;

    }

}


